import threading

from pynput import keyboard


class keyboardListener():

    def __init__(self):
        self.keyboard_listener = keyboard.Listener(on_press=self.on_key_press, on_release=self.on_key_release)

    # 定义一个回调函数来处理按键事件
    def on_key_press(self, key):
        try:
            print(f"按键 {key.char} 被按下")
        except AttributeError:
            print(f"特殊按键 {key} 被按下")

    def on_key_release(self, key):
        print(f"按键 {key} 被释放")

    def listener_start(self):
        self.keyboard_listener.start()

    def listener_stop(self):
        self.keyboard_listener.join()


def thread_start_listener():
    # 创建键盘监听器对象
    listener = keyboardListener()

    listener_thread = threading.Thread(target=listener.listener_start, name="listener线程")

    listener_thread.start()
